package com.mgy.api.framework.core.filter;

import com.mgy.api.framework.core.constant.Constant;
import com.mgy.api.framework.core.handler.ApiFrameworkProperties;
import org.springframework.util.StringUtils;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 启用swagger时兼容生成api文档及测试调用接口
 *
 * @author mgy
 * @date 2019.11.15
 */
public class ForwardFilter implements Filter {

    public ApiFrameworkProperties getProperties() {
        return properties;
    }

    public void setProperties(ApiFrameworkProperties properties) {
        this.properties = properties;
    }

    private ApiFrameworkProperties properties;


    private boolean isFilter() {
        if (properties != null && properties.isEnable() && properties.getSwagger() != null && properties.getSwagger().isEnable()) {
            return true;
        }
        return false;
    }


    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        if (isFilter()) {
            String method = request.getParameter(Constant.METHOD);
            String oldUrl = request.getRequestURI();
            if (oldUrl.startsWith(properties.getRootPath()) && StringUtils.hasText(method) && !oldUrl.endsWith(method)) {
                String newUrl;
                if (oldUrl.endsWith("/")) {
                    newUrl = oldUrl + method;
                } else {
                    newUrl = oldUrl + "/" + method;
                }
                request.getRequestDispatcher(newUrl).forward(request, servletResponse);
                return;
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
